from django.contrib import admin
from .models import DataSource, OPCUASubscription, MQTTSubscription, MqttSubscriptionItem

@admin.register(DataSource)
class DataSourceAdmin(admin.ModelAdmin):
    """数据源管理"""
    list_display = ['name', 'type', 'connection_string', 'created_by', 'created_at']
    list_filter = ['type', 'created_at', 'created_by']
    search_fields = ['name', 'connection_string', 'description']
    readonly_fields = ['created_by', 'created_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']

    def save_model(self, request, obj, form, change):
        """保存模型时自动设置创建者"""
        if not change:  # 只在创建时设置
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

    def has_module_permission(self, request):
        """检查用户是否有查看模块的权限"""
        return request.user.is_staff

    def has_add_permission(self, request):
        """检查用户是否有添加权限"""
        return request.user.has_perm('subscriptions.add_datasource')

    def has_change_permission(self, request, obj=None):
        """检查用户是否有修改权限"""
        return request.user.has_perm('subscriptions.change_datasource')

    def has_delete_permission(self, request, obj=None):
        """检查用户是否有删除权限"""
        return request.user.has_perm('subscriptions.delete_datasource')

    def has_view_permission(self, request, obj=None):
        """检查用户是否有查看权限"""
        return request.user.is_staff

@admin.register(OPCUASubscription)
class OPCUASubscriptionAdmin(admin.ModelAdmin):
    """OPC UA订阅管理"""
    list_display = ['data_source', 'node_id', 'condition', 'threshold_value', 'is_active', 'created_by', 'created_at']
    list_filter = ['data_source', 'is_active', 'created_at', 'created_by']
    search_fields = ['node_id', 'alert_message']
    readonly_fields = ['created_by', 'created_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

@admin.register(MQTTSubscription)
class MQTTSubscriptionAdmin(admin.ModelAdmin):
    """MQTT订阅管理"""
    list_display = ['data_source', 'topic', 'is_active', 'created_by', 'created_at']
    list_filter = ['data_source', 'is_active', 'created_at', 'created_by']
    search_fields = ['topic']
    readonly_fields = ['created_by', 'created_at']
    date_hierarchy = 'created_at'
    ordering = ['-created_at']

    def save_model(self, request, obj, form, change):
        if not change:
            obj.created_by = request.user
        super().save_model(request, obj, form, change)

@admin.register(MqttSubscriptionItem)
class MqttSubscriptionItemAdmin(admin.ModelAdmin):
    """MQTT订阅项管理"""
    list_display = ['subscription', 'values_id', 'condition', 'threshold_value', 'is_active']
    list_filter = ['subscription', 'is_active']
    search_fields = ['values_id', 'alert_message']
    ordering = ['subscription', 'values_id']
